package com.example.gulimallproduct.exception;

import com.example.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestControllerAdvice(basePackages = "com.example.gulimallproduct.controller")
public class gulimallProductException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R hanleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}, 异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map=new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(400,"数据校验异常").put("data",map);
    }

//    @ExceptionHandler(value = Throwable.class)
//    public R handleException(Throwable throwable){
//        System.out.println(throwable);
//        return R.error();
//    }
}
